<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>修改元素属性</title>

        <style>
            .wrapper { margin: auto ; }
            
            .password-wrapper {
                height: 50px ;
                width: 300px ;
                border: 1px solid #dedede ;
                border-radius: 5px ;
                overflow: hidden ;
            }

            .password-wrapper>* {
                float: left ;
            }

            .password-wrapper>label {
                width: 14% ;
                height: 50px ;
                line-height: 50px ;
                text-align: center ;
                user-select: none ;
            }

            .password-wrapper>input {
                width: 70% ;
                height: 50px ;
                line-height: 50px ;
                border: none ;
                outline: none ;
            }

            .password-wrapper>span {
                width: 14% ;
                height: 50px ;
                line-height: 50px ;
                text-align: center ;
                user-select: none ;
            }
        </style>
    </head>
    <body>

        <div class="wrapper password-wrapper">
            <label>密码</label>
            <input type="password" 
                   name="password" 
                   autofocus 
                   onfocus="x.change(this)" 
                   onblur="x.recover(this)">
            <span onclick="x.toggle(this)">显示</span>
        </div>

        <script>
            let x = {
                change: function( input ){
                    console.log( input );
                    let p = input.parentElement ;
                    p.style.borderColor = 'blue' ;
                },
                recover: function( input ){
                    let p = input.parentElement ;
                    p.style.borderColor = '#dedede' ;
                },
                toggle: function( span ){
                    console.log( span );
                    // 获得 span 前一个兄弟元素
                    let input = span.previousElementSibling;
                    console.log( input );

                    let value = input.getAttribute( 'type' );
                    if( value.toLowerCase() === 'password' ) {
                        input.setAttribute( 'type' , 'text');
                        span.innerText = '隐藏' ;
                        return ;
                    }

                    if( value.toLowerCase() === 'text' ) {
                        input.setAttribute( 'type' , 'password');
                        span.innerText = '显示' ;
                        return ;
                    }
                }
            }
        </script>
        
    </body>
</html>